<template>
  <div class="otherContainer">
    <div class="tempSearchContainer">
      <div class="siteSearch">
        &nbsp;<span style="color: red">*&nbsp;</span
        >运单号：&nbsp;&nbsp;&nbsp;{{ waybill_code }}
        <!-- <el-select
          v-model="selectedCode"
          :disabled="true"
          filterable
          remote
          reserve-keyword
          :remote-method="remoteMethod"
          :loading="loading"
          @focus="getCodeList"
          @change="searchOrderTemp(selectedCode)"
        >
          <el-option
            v-for="item in displayCode"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select> -->
      </div>
      <!-- <div class="siteSearch">
        物流公司&nbsp;&nbsp;&nbsp;
        <el-select
          v-model="selectedCompany"
          filterable
          remote
          :remote-method="remoteMethodCompany"
          reserve-keyword
          placeholder="选择物流公司"
          :loading="loading"
          @focus="getCompanyList"
        >
          <el-option
            v-for="item in displayCompany"
            :key="item.value"
            :label="item.label"
            :value="item.value"
          >
          </el-option>
        </el-select>
      </div>
      <div class="siteSearch">
        快递单号&nbsp;&nbsp;&nbsp;
        <el-input
          size="mini"
          v-model="expressCode"
          placeholder="请输入内容"
        ></el-input>
      </div> -->
      <div class="siteSearch">
        是否显示承运商：
        <el-radio-group v-model="is_show_carrier_logistics">
          <el-radio label="1">是</el-radio>
          <el-radio label="0">否</el-radio>
        </el-radio-group>
      </div>
      <el-button
        data-tracker="P4-46"
        type="primary"
        @click="handleSetOk"
        style="margin-left: 15px"
        >确认</el-button
      >
      <div class="tempList">
        <el-card class="card3">
          <div style="font-size: 14px; margin-bottom: 10px">物流节点信息</div>
          <!-- <div
            v-if="!activities.length"
            style="
              border: 1px solid #ebeef5;
              text-align: center;
              font-size: 12px;
              line-height: 60px;
              width: 100%;
              color: #909399;
            "
          >
            暂无数据
          </div> -->
          <waybillTrack
            ref="nodeTrack"
            :origin="'node'"
            :id="id"
          ></waybillTrack>

          <!-- <el-timeline v-if="activities.length">
            <el-timeline-item
              v-for="(activity, index) in activities"
              :key="index"
              :color="activity.color"
              :timestamp="
                activity.time
                  ? new Date(Number(activity.time) * 1000)
                      .toLocaleString()
                      .replace(/:\d{1,2}$/, ' ')
                  : ''
              "
            >
              <div>
                <span v-show="activity.arrival_position"
                  >待配送：{{ activity.arrival_position }}</span
                >&nbsp;&nbsp;&nbsp;&nbsp;
                <span v-show="activity.send_position"
                  >发往：{{ activity.send_position }}</span
                >
              </div>
              <div>
                <span v-show="activity.operation_content">{{
                  activity.operation_content
                }}</span>
                <span v-show="activity.temperature_content">{{
                  activity.temperature_content
                }}</span>
              </div>
            </el-timeline-item>
          </el-timeline> -->
        </el-card>
        <el-card class="card1">
          <div style="font-size: 14px; margin-bottom: 10px">编辑物流节点</div>
          <el-table
            :data="tableData"
            style="width: 100%"
            :height="tableData.length ? '300' : '100'"
            border
          >
            <el-table-column label="时间" width="200" prop="time">
            </el-table-column>
            <el-table-column label="到达位置" width="200" prop="arriveSite">
            </el-table-column>
            <el-table-column label="发往位置" width="200" prop="leaveSite">
            </el-table-column>
            <el-table-column label="操作内容" prop="actContent">
            </el-table-column>
            <!-- <el-table-column label="温度" prop="temp" width="200">
            </el-table-column> -->
            <el-table-column label="操作" width="80">
              <template slot-scope="scope">
                <el-button
                  size="mini"
                  type="danger"
                  v-permission="'order_trajectory_delete'"
                  @click="handleDelete1(scope.$index, scope.row)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        <el-card class="card2" v-permission="'order_trajectory_add'">
          <el-button
            type="primary"
            @click="addOneLine"
            data-tracker="P4-47"
            style="margin-bottom: 10px"
          >
            增加一条
          </el-button>
          <div class="oneLine" v-for="n in lineNum" :key="n">
            <el-form
              ref="form"
              :model="form[n - 1]"
              label-width="70px"
              :inline="true"
              label-position="left"
            >
              <el-form-item label="时间">
                <el-date-picker
                  v-model="form[n - 1].time"
                  type="datetime"
                  placeholder="选择日期时间"
                  style="width: 180px"
                >
                </el-date-picker>
              </el-form-item>
              <el-form-item label="到达位置">
                <el-input
                  v-model="form[n - 1].arriveSite"
                  style="width: 150px"
                ></el-input>
              </el-form-item>
              <el-form-item label="发往位置">
                <el-input
                  v-model="form[n - 1].leaveSite"
                  style="width: 150px"
                ></el-input>
              </el-form-item>
              <el-form-item label="操作内容">
                <el-input
                  v-model="form[n - 1].actContent"
                  style="width: 184px"
                ></el-input>
              </el-form-item>
              <!-- <el-form-item label="温度">
                <el-input
                  v-model="form[n - 1].temp"
                  placeholder="多个温度用逗号隔开"
                  style="width: 140px"
                ></el-input>
              </el-form-item> -->
              <el-form-item>
                <el-button
                  data-tracker="P4-48"
                  type="danger"
                  @click="deleteOneLine"
                >
                  删除
                </el-button>
              </el-form-item>
            </el-form>
          </div>
          <el-button
            type="primary"
            style="margin-left: 600px"
            @click="submitTemp"
            data-tracker="P4-49"
            v-permission="'order_trajectory_add'"
            >保存</el-button
          >
        </el-card>
      </div>
    </div>
  </div>
</template>

<script>
import { getToken } from "@/utils/auth";
import {
  reqOrdersCode,
  // reqOrderTemp,
  reqOrderDetail,
  deleteOrderDetail,
  addOrderDetail,
  reqTransCompany,
  reqTransInfo,
  reqTempAndGps,
} from "@/api/orderForm";
import { WaybillDetailFn, carrierLogisticsUpdate } from "@/api/waybill";
import waybillTrack from "@/page/waybill/waybillDetailPage/components/waybillTrack";

import moment from "moment";
export default {
  name: "logisticsManage",
  props: ["id"],
  components: {
    waybillTrack,
  },
  data() {
    return {
      codeList: [], //服务器数据
      selectedCode: [],
      waybill_code: "",
      companyList: [], //服务器数据
      displayCode: [],
      displayCompany: [],
      loading: false,
      tableData: [],
      form: [
        {
          time: new Date(new Date().setHours(0, 0, 0, 0)),
          arriveSite: "",
          leaveSite: "",
          actContent: "",
          temp: "",
        },
      ],
      lineNum: 1,
      token: "",
      timeRange: [
        new Date(new Date().setHours(0, 0, 0, 0)),
        new Date(new Date().setHours(23, 59, 59, 59)),
      ],
      selectedCompany: "", //选中的的物流公司
      expressCode: "", //输入的快递单号
      radio: "", //隐藏
      activities: [
        {
          time: "2022-08-01 15:30:31",
          context: "送回北京办公室",
          color: "#fdb521",
        },

        {
          time: "2022-08-01 13:44:36",
          context: "到站北京",
        },

        {
          time: "2022-07-28 16:05:11",
          context: "配载火车",
        },

        {
          time: "2022-07-28 09:44:23",
          context: "取件完成",
        },
        {
          time: "2022-07-27 12:11:33",
          context: "运单生成",
        },
      ],
      manufacturerList: [
        { value: "鲁尔", label: "鲁尔" },
        { value: "精创", label: "精创" },
        { value: "易流云", label: "易流云" },
      ],
      manufacturer: "", //选择的厂商
      deviceNumber: "", //设备编号
      // deviceType: "", //设备型号
      positionList: [], //物流位置信息
      noPositionList: [], //没有位置信息显示空
      tempTable: [], //温度表格信息
      showPosition: true, //若没有位置信息的话打印就不显示
      is_show_carrier_logistics: "", //是否显示承运商
    };
  },
  mounted() {
    WaybillDetailFn({ id: this.id }).then((result) => {
      this.waybill_code = result.data.waybill_number;
      this.is_show_carrier_logistics = result.data.is_show_carrier_logistics;
    });
    this.submitTrans();
    this.$nextTick(() => {
      // console.log(this.$refs.nodeTrack.getNode,'nodeTrack------------')
    });
  },
  methods: {
    handleSetOk() {
      carrierLogisticsUpdate({
        waybill_id: this.id + "",
        is_show_carrier_logistics: this.is_show_carrier_logistics,
      }).then((res) => {
        if (res.code === 10000) {
          this.$message({
            type: "success",
            message: "设置成功",
          });
          this.submitTrans();
        }
      });
    },
    async getCodeList() {
      let result = await reqOrdersCode(this.token);
      this.codeList = result.data.list.map((item) => {
        return {
          value: `${item.order_code}`,
          label: `${item.order_code}`,
        };
      });
      this.displayCode = this.codeList;
    },
    remoteMethod(query) {
      if (query !== "") {
        this.loading = true;
        setTimeout(() => {
          //前端做的模糊查询
          this.loading = false;
          this.displayCode = this.codeList.filter((item) => {
            return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
          });
        }, 200);
      } else {
        this.displayCode = [];
      }
    },
    async searchOrderTemp(code) {
      //选中订单号之后的请求和显示数据
      const token = this.token;
      this.submitTrans();
      let result = await reqOrderDetail({ code, token });
      let list = result.data.map((item) => {
        return {
          time: moment(new Date(Number(item.create_ts)).getTime()).format(
            "YYYY-MM-DD HH:mm:ss"
          ), //一定要Date格式才能用moment转,然后Date()里面只能接收数字类型
          address: item.position,
          temp: item.temperature.toString(),
          id: item.tp_id,
        };
      });
      this.tableData = list;
    },
    async handleDelete1(index, row) {
      await deleteOrderDetail({
        id: row.id,
      });
      this.tableData.splice(index, 1);
      this.submitTrans();
    },
    addOneLine() {
      this.lineNum++;
      this.form.push({
        time: "",
        arriveSite: "",
        leaveSite: "",
        actContent: "",
        temp: "",
      });
    },
    deleteOneLine() {
      if (this.lineNum > 1) {
        this.lineNum--;
        this.form.splice(this.lineNum, 1);
      } else {
        this.$message({
          type: "error",
          message: "至少保留一行",
        });
      }
    },
    submitTemp() {
      this.form.forEach(async (item) => {
        await addOrderDetail({
          // order_code: this.selectedCode,
          // time: new Date(item.time).getTime().toString(), //给后端发送时间戳格式(要是字符串)
          // address: item.address,
          // temperature: item.temp.split("，")[0].split(","), //中文逗号和英文逗号都行
          // token: this.token,
          order_id: "",
          waybill_id: this.id,
          time: String(Number(item.time) / 1000),
          arrival_position: item.arriveSite,
          send_position: item.leaveSite,
          operation_content: item.actContent,
          temperature_content: item.temp,
        });
        this.submitTrans();
      });
    },
    async getCompanyList() {
      let result = await reqTransCompany();
      this.companyList = result.data.map((item) => {
        return {
          value: `${item.logistics_name}`,
          label: `${item.logistics_name}`,
        };
      });
      this.displayCompany = this.companyList;
    },
    remoteMethodCompany(query) {
      if (query !== "") {
        this.loading = true;
        setTimeout(() => {
          this.loading = false;
          this.displayCompany = this.companyList.filter((item) => {
            return item.label.toLowerCase().indexOf(query.toLowerCase()) > -1;
          });
        }, 200);
      } else {
        this.displayCompany = [];
      }
    },
    async submitTrans() {
      this.activities = [];
      let result = await reqTransInfo({
        order_id: "",
        waybill_id: this.id,
        is_replace: this.radio === "是" ? "1" : "0",
      });
      if (result.data.data.length > 0) {
        let list = result.data.data.map((item) => {
          return {
            id: item.id,
            time: new Date(Number(item.time) * 1000)
              .toLocaleString()
              .replace(/:\d{1,2}$/, " "),
            arriveSite: item.arrival_position,
            leaveSite: item.send_position,
            actContent: item.operation_content,
            temp: item.temperature_content,
          };
        });
        this.tableData = list;
        this.activities.push(
          Object.assign(result.data.data[0], { color: "#e69850" })
        );
        for (var i = 1; i < result.data.data.length; i++) {
          this.activities.push(result.data.data[i]);
        }
      }

      this.$refs.nodeTrack.getNode();
    },
  },
};
</script>

<style scoped lang="less">
.otherContainer {
  width: 100%;
  height: auto;
  overflow: auto;
  .tempSearchContainer {
    background-color: #fff;
    padding: 0 20px;
    .siteSearch {
      font-size: 12px;
      margin-bottom: 15px;
      display: inline-block;
      width: 300px;
      .el-input {
        width: 180px;
      }
    }
    .card3 {
      margin-bottom: 10px;
    }
    .tempList {
      margin-top: 10px;
      .card1 {
        margin-bottom: 10px;
      }
    }
  }
  .tempAndSiteContainer {
    .timeSearch {
      font-size: 12px;
      margin-bottom: 20px;
      display: inline-block;
      width: 300px;
      .el-input {
        width: 180px;
      }
    }
  }
}
</style>